<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\WechatValue;
use App\Models\Wechat;
use App\Http\Requests\WechatUpdateRequest;
use Excel;
class WechatValueController extends Controller
{
    protected $fields = [
		'uid' => 0,
        'wechat_id' => 0,
        'key' => '',
		'value' => '',
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,$wid)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
			$uid = auth()->user()->id;
			$count = WechatValue::where(function ($query) use ($uid){
					if($uid!=1){
						$query->where('uid','=',auth()->user()->id);
					}
				})->where('wechat_id',$wid)->count();
            $data['recordsTotal'] = $count;
				
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = WechatValue::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%');
                })->where(function ($query) use ($uid){
					if($uid!=1){
						$query->where('uid','=',auth()->user()->id);
					}
				})->where('wechat_id',$wid)->count();
				
                $data['data'] = WechatValue::select('wechat_values.*','wechats.wx_num')
					->leftJoin("wechats","wechats.id","=","wechat_values.wechat_id")
					->where(function ($query) use ($search) {
						$query->where('wechat_values.name', 'LIKE', '%' . $search['value'] . '%');
					})
					->where(function ($query) use ($uid){
						if($uid!=1){
							$query->where('uid','=',auth()->user()->id);
						}
					})
					->where('wechat_id',$wid)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
				$data['recordsFiltered'] = $count;						
                $data['data'] = WechatValue::select('wechat_values.*','wechats.wx_num')
					->leftJoin("wechats","wechats.id","=","wechat_values.wechat_id")
					->where(function ($query) use ($uid){
						if($uid!=1){
							$query->where('wechat_values.uid','=',auth()->user()->id);
						}
					})
					->where('wechat_id',$wid)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        return view('admin.wechatvalue.index',['wid'=>$wid]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($wid)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
		$data['wx_num'] = Wechat::where('id', $wid)->value('wx_num');
        $data['wechat_id'] = $wid;
        return view('admin.wechatvalue.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		if($this->validateValue($request->wechat_id,$request->key)>0){ return redirect()->back()->withErrors('key重复！');}
		//$this->validate($request,['key'=>'required|unique:wechat_values']);
		//if($this->validWechatValue($request->get('name'),auth()->user()->id!=1?auth()->user()->id:$request->get('uid'))) return redirect('/admin/wechatgroup/create')->withErrors("已有该分组!");
        $wechatvalue = new WechatValue();
        foreach (array_keys($this->fields) as $field) {
			if($field=='uid'){
				$wechatvalue->$field = auth()->user()->id;
				continue;
			}
			$wechatvalue->$field = $request->get($field);
        }
		$wechatvalue->save();
		event(new \App\Events\userActionEvent('\App\Models\WechatValue',$wechatvalue->id, 1, '新增了调用值['.$wechatvalue->key.']' ));
        return redirect('/admin/wechatvalue/'.$request->get('wechat_id').'/index')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       $wechatvalue = WechatValue::find((int)$id);
       if (!$wechatvalue) return redirect()->back()->withErrors("找不到该调用值!");
       foreach (array_keys($this->fields) as $field) {
           $data[$field] = old($field, $wechatvalue->$field);
       }
	   $data['wx_num'] = Wechat::where('id', $wechatvalue->wechat_id)->value('wx_num');
       $data['id'] = (int)$id;
       return view('admin.wechatvalue.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		if($this->validateValue($request->wechat_id,$request->key)>0&&$this->validateValue($request->wechat_id,$request->key)!=$id){ return redirect()->back()->withErrors('key重复！');}
		//$this->validate($request,['key'=>'required|unique:wechat_values,id,'.$id]);
        $wechatvalue = WechatValue::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
			if($field=='uid'){
				continue;
			}
            $wechatvalue->$field = $request->get($field);
        }
        $wechatvalue->save();
		event(new \App\Events\userActionEvent('\App\Models\WechatValue',$id, 3, '更新键为['.$wechatvalue->key.']的微信调用值='.$request->get('value')));
        return redirect('/admin/wechatvalue/'.$request->get('wechat_id').'/index')->withSuccess('更新成功！');
    }
	public function cogsUpdate(Request $request){
		$keys = $request->input('key');
		if(count($keys)==0){ return redirect()->back()->withErrors('请选择需要更新的键'); }
		if($request->get('value')==''){ return redirect()->back()->withErrors('请输入需要更新的值'); }
		$where = '1!=1';
		foreach($keys as $val){
			$where .= " or id=".$val;
		}
		WechatValue::whereRaw($where)->update(['value'=>''.$request->get('value')]);
		$wvs = WechatValue::select("key")->whereRaw($where)->get();
		$wx = "[";
		foreach($wvs as $wv){ $wx.=$wv->key."、";}
		$wx .="]";
		event(new \App\Events\userActionEvent('\App\Models\WechatValue',0, 3, '批量更新键为'.$wx.'微信调用值='.$request->get('value')));
		return redirect()->back()->withSuccess('更新成功！');
	}

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = WechatValue::find((int)$id);
            if ($tag) {
				$key = $tag->key;
                $tag->delete();
				event(new \App\Events\userActionEvent('\App\Models\WechatValue',$id, 2, '删除了调用值['.$key.']'));
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
			$wvs =  WechatValue::select('key')->whereIn('id',$idArr)->get();
			$wx = "[";
			foreach($wvs as $wv){ $wx.=$wv->key."、";}
			$wx .="]";
            $recordRow =WechatValue::whereIn('id',$idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\WechatValue',$id, 2, '批量删除了调用值'.$wx));
            if(!$recordRow){
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	function validateValue($id,$key){
		$tag = WechatValue::where('wechat_id',$id)->where('key',$key)->first();
		if(!$tag){
			return 0;
		}else{
			return $tag->id;
		}
	}
	//批量导入
	public function leading($wid = 0)
    {
		$data['wid'] = $wid;
		return view('admin.wechatvalue.leading', $data);
    }
	//批量导入保存
	public function import(Request $request){
		if($request->hasFile('wechatvalue')){
			$file = $request->file('wechatvalue');
			if ($file->isValid()){
				$str = explode('.',$file->getClientOriginalName());
				$fileName = time().'.'.$str[count($str)-1];
				$file->move(config('app.templates_xlsx_path'),$fileName);
				unset($file);
				$excel = Excel::load(config('app.templates_xlsx_path').$fileName)->toArray();
				$validates = WechatValue::where('wechat_id',$request->get('wid'))->lists('key')->toArray();
				$log_txt= "";$datas=[];
				foreach($excel[0] as $k=>$exc){
					if(in_array($exc['key']."",$validates)){
						$log_txt.=$exc['key']."-冲突\n";
						continue;
					}
					$data['key']= $exc['key'];
					$data['value']= $exc['value'];
					$data['uid']= auth()->user()->id;
					$data['uid']= auth()->user()->id;
					$data['wechat_id']= $request->get('wid');
					$data['created_at']= date('Y-m-d H:i:s');
					$data['updated_at']= date('Y-m-d H:i:s');
					$datas[]=$data;
				}
				$wechatvalue = new WechatValue();
				$wechatvalue->insert($datas);
				unlink(config('app.templates_xlsx_path').'/'.$fileName);
				if($log_txt!=""){
					file_put_contents(config('app.templates_xlsx_path').'/'.$fileName.'.log',$log_txt);
					return redirect('/admin/wechatvalue/'.$request->get('wid')."/index")->withSuccess('导入成功！冲突日志：http://'. $_SERVER["HTTP_HOST"].config('app.templates_xlsx_path').$fileName.'.log'); 
				}else{
					return redirect('/admin/wechatvalue/'.$request->get('wid')."/index")->withSuccess('导入成功！没有冲突域名。');
				}
				
			}else{
				return redirect('/admin/wechatvalue/leading/'.$request->get('wid'))->withErrors('文件无效！'); 
			}
		}else{
			return redirect('/admin/wechatvalue/leading/'.$request->get('wid'))->withErrors('请上传文件！'); 
		}
	}
}